import os
import base64
from datetime import datetime
import logging

from rest_framework import viewsets
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.decorators import api_view

from django.conf import settings
from .models import Template
from .serializers import TemplateSerializer
from .utils.db_manager import db_manager

logger = logging.getLogger(__name__)

class TemplateViewSet(viewsets.ModelViewSet):
    queryset = Template.objects.all()
    serializer_class = TemplateSerializer

    @action(detail=False, methods=['get'])
    def experiments(self, request):
        """获取实验列表"""
        try:
            experiments = db_manager.get_experiments()
            return Response(experiments)
        except Exception as e:
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    @action(detail=False, methods=['get'])
    def experiment_info(self, request):
        """获取实验详细信息"""
        experiment_id = request.query_params.get('experiment_id')
        if not experiment_id:
            return Response(
                {'error': '实验ID不能为空'}, 
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            experiment = db_manager.get_experiment_by_id(experiment_id)
            if not experiment:
                return Response(
                    {'error': '实验不存在'}, 
                    status=status.HTTP_404_NOT_FOUND
                )

            time_range = db_manager.get_experiment_time_range(experiment_id)
            experiment.update(time_range or {})
            
            return Response(experiment)
        except Exception as e:
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    @action(detail=False, methods=['get'])
    def experiment_channels(self, request):
        """获取实验的通道列表"""
        experiment_id = request.query_params.get('experiment_id')
        if not experiment_id:
            return Response(
                {'error': '实验ID不能为空'}, 
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            channels = db_manager.get_experiment_channels(experiment_id)
            return Response(channels)
        except Exception as e:
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

class ExperimentDataViewSet(viewsets.ViewSet):
    @action(detail=False, methods=['get'])
    def get_data(self, request):
        """获取实验数据"""
        try:
            experiment_id = request.query_params.get('experimentId')
            start_time = request.query_params.get('startTime')
            end_time = request.query_params.get('endTime')
            page = request.query_params.get('page')
            page_size = request.query_params.get('pageSize')

            data = db_manager.get_experiment_data(
                experiment_id=experiment_id if experiment_id or experiment_id != 'undefined' else None,
                start_time=float(start_time) if start_time else None,
                end_time=float(end_time) if end_time else None,
                page=float(page) if page else 1,
                page_size=float(page_size) if page_size else 50
            )
            
            return Response(data)
        except Exception as e:
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

class ExperimentLogViewSet(viewsets.ViewSet):
    @action(detail=False, methods=['get'])
    def get_parameters(self, request):
        """获取实验参数"""
        try:
            experiment_id = request.query_params.get('experimentId')
            experiment_id = None if not experiment_id else experiment_id

            data = db_manager.get_experiment_parameters(experiment_id)
            return Response(data)
        except Exception as e:
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    @action(detail=False, methods=['get'])
    def get_images(self, request):
        """获取实验图片列表"""
        try:
            experiment_id = request.query_params.get('experimentId')
            if not experiment_id:
                return Response(
                    {'error': '实验ID不能为空'}, 
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 构建完整的图片路径
            experiment_path = os.path.join(settings.CHART_SAVE_PATH, str(experiment_id))
            print(f"Looking for images in: {experiment_path}")  # 调试日志
            
            if not os.path.exists(experiment_path):
                print(f"Directory not found: {experiment_path}")
                return Response({'images': []})

            images = [
                f for f in os.listdir(experiment_path)
                if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))
            ]

            print(f"Found images: {images}")  # 调试日志
            return Response({
                'images': sorted(images),
                'path': f"images/{experiment_id}"  # 返回相对路径
            })
            
        except Exception as e:
            print(f"Error getting images: {str(e)}")
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

class CurveDataViewSet(viewsets.ViewSet):
    """曲线数据视图集"""

    @action(detail=False, methods=['post'])
    def get_curve_data(self, request):
        """获取曲线数据"""
        try:
            data = request.data
            experiment_id = data.get('experimentId')
            channels = data.get('channels', [])
            time_range = data.get('timeRange', {})
            
            if not experiment_id or not channels or not time_range:
                return Response(
                    {'error': '参数不完整'},
                    status=status.HTTP_400_BAD_REQUEST
                )

            start_time = float(time_range.get('start'))
            end_time = float(time_range.get('end'))
            
            if not start_time or not end_time:
                return Response(
                    {'error': '时间范围参数不完整'},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 获取曲线数据
            curve_data = {}
            for channel in channels:
                channel_data = db_manager.get_channel_data(
                    channel['experimentId'],
                    channel['channel'],
                    start_time,
                    end_time
                )

                # 组合通道数据和配置信息
                curve_data[channel['channel']] = {
                    'data': channel_data,
                    'config': {
                        'color': channel.get('color', '#1890FF'),
                        'unit': channel.get('unit', ''),
                        'position': channel.get('position', '1')
                    }
                }

            return Response({
                'code': 200,
                'message': '获取数据成功',
                'data': {
                    'experimentId': experiment_id,
                    'experimentName': data.get('experimentName', ''),
                    'timeRange': time_range,
                    'channels': curve_data
                }
            })

        except Exception as e:
            logger.error(f"获取曲线数据失败: {str(e)}")
            return Response(
                {
                    'code': 500,
                    'message': f'获取曲线数据失败: {str(e)}',
                    'error': str(e)
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    @action(detail=False, methods=['get'])
    def get_channel_info(self, request):
        """获取通道配置信息"""
        try:
            experiment_id = request.query_params.get('experimentId')
            if not experiment_id:
                return Response(
                    {'error': '实验ID不能为空'},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 获取通道配置信息
            channel_info = db_manager.get_channel_info(experiment_id)
            
            return Response({
                'code': 200,
                'message': '获取通道信息成功',
                'data': channel_info
            })

        except Exception as e:
            logger.error(f"获取通道信息失败: {str(e)}")
            return Response(
                {
                    'code': 500,
                    'message': f'获取通道信息失败: {str(e)}',
                    'error': str(e)
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

@api_view(['POST'])
def save_chart_image(request):
    try:
        image_data = request.data.get('imageData')
        experiment_id = request.data.get('experimentId')

        # 从配置文件读取保存路径
        save_dir = os.path.join(settings.CHART_SAVE_PATH, str(experiment_id))
        os.makedirs(save_dir, exist_ok=True)

        # 生成文件名
        timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
        filename = f"{experiment_id}_{timestamp}.png"
        file_path = os.path.join(save_dir, filename)

        # 解码并保存图片
        image_data = image_data.split(',')[1]  # 移除 base64 头部信息
        image_bytes = base64.b64decode(image_data)
        
        with open(file_path, 'wb') as f:
            f.write(image_bytes)

        return Response({
            'message': 'Image saved successfully',
            'path': file_path
        })

    except Exception as e:
        return Response({
            'error': str(e)
        }, status=500)
